package com.hdl.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import com.hdl.dao.AddressDao;
import com.hdl.entity.MallAddress;
import com.hdl.util.Druidutils;
import com.hdl.util.JdbcUtil;

public class AddressDaoImpl implements AddressDao{

	private JdbcTemplate template = new JdbcTemplate(Druidutils.getDataSource());
	private Connection conn = JdbcUtil.getConnection();
	private PreparedStatement pstm = null;
	private ResultSet rs = null;
	
	@Override
	public List<MallAddress> getAllByUserId(String userId) {
		
		//定义sql语句
		String sql = "select * from mall_address where HDL_USER_ID = ? ";
		template.query(sql, new BeanPropertyRowMapper<MallAddress>(MallAddress.class),userId);
		return template.query(sql, new BeanPropertyRowMapper<MallAddress>(MallAddress.class),userId);
	}

	@Override
	public MallAddress selectByAddressId(String mallAddressId) {
		
		//定义sql语句
		String sql = "select * from mall_address where MALL_ADDRESS_ID = ? ";
		return template.queryForObject(sql, new BeanPropertyRowMapper<MallAddress>(MallAddress.class),mallAddressId);
	}
	
	
	public List<MallAddress> getAllNameByAddress(List<MallAddress> list){
		String pid = "";
		List<MallAddress> nameList = new ArrayList<MallAddress>();
		for (MallAddress mallAddress : list) {
			StringBuilder sb = new StringBuilder("");
			String sql = "select * from sys_areas where id = ? ";
				try {
					pstm = conn.prepareStatement(sql);
					pstm.setObject(1, mallAddress.getMallAddressCode());
					rs = pstm.executeQuery();
					if(rs.next()) {
						pid = rs.getString("pid");
						sb = sb.insert(0, rs.getString("NAME"));
					}else {
						throw new RuntimeException("id查询没有记录");
					}
					for(int i = 0; i< 4; i++) {
						pstm = conn.prepareStatement(sql);
						pstm.setObject(1, pid);
						rs = pstm.executeQuery();
						if(rs.next()) {
							pid = rs.getString("pid");
							sb = sb.insert(0, rs.getString("NAME"));
						}else {
							throw new RuntimeException("id查询没有记录");
						}
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			mallAddress.setMallAddressDetail(sb.toString());
			nameList.add(mallAddress);
		}
		return nameList;
	}

}
